<?php

/**
 * jwCustomTable form.
 *
 * @package    ##PROJECT_NAME##
 * @subpackage form
 * @author     ##AUTHOR_NAME##
 * @version    SVN: $Id: sfPropelFormTemplate.php 10377 2008-07-21 07:10:32Z dwhittle $
 */
class jwCustomTableForm extends BasejwCustomTableForm
{
  public function configure()
  {
    $this->setWidgets(array(
      'id'          => new sfWidgetFormInputHidden(),
      'type'        => new sfWidgetFormInput(),
      'name'        => new sfWidgetFormInput(),
      'description' => new sfWidgetFormTextarea(),
      'values'        => new jwWidgetTableValues(),
    ));

    $this->setValidators(array(
      'id'          => new sfValidatorPropelChoice(array('model' => 'jwCustomTable', 'column' => 'id', 'required' => false)),
      'type'        => new sfValidatorString(array('max_length' => 100, 'required' => false)),
      'name'        => new sfValidatorString(array('max_length' => 255, 'required' => false)),
      'description' => new sfValidatorString(array('required' => false)),
      'values' => new sfValidatorString(array('required' => false)),
    ));
    
    $this->setDefault( 'values', $this->getObject()->getValuesAsJSON() );

    $this->widgetSchema->setNameFormat('jw_custom_table[%s]');

    $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);
  }
  
  public function bind( array $taintedValues = null, array $taintedFiles = null )
  {
	jwCustomTableForm::updateFromRequest( $this, &$taintedValues );

    parent::bind( $taintedValues, $taintedFiles );
  }
  
  public static function updateFromRequest( sfForm &$form, array &$taintedValues = null )
  {
    $form->getObject()->clearjwCustomTableValues();
    $form->getObject()->forceUpdate();
    if ( isset( $taintedValues['values'] ) )
    {
      $value = $taintedValues['values'];
      $value = str_replace( ",}", "}", $value );
      $value = str_replace( "'", "\"", $value );


      $value = json_decode( $value, true );
      
      

      foreach( $value as $rowIndex => $row )
      {
        foreach( $row as $colIndex => $value )
        {
          unset( $jwTableValue );
          $jwTableValue = null;
          if ( !$form->getObject()->isNew() )
          {
            // try to retrieve the value object
            $jwTableValue = jwCustomTableValuePeer::retrieveByPK( $form->getObject()->getId(), $rowIndex, $colIndex );
          }
          
          if ( !$jwTableValue )
          {
            $jwTableValue = new jwCustomTableValue();
          }
          
          $jwTableValue->setRow( $rowIndex );
          $jwTableValue->setCol( $colIndex );
          $jwTableValue->setValue( $value );
          
          $form->getObject()->addjwCustomTableValue( $jwTableValue );
        }
      }
    }	
  }  
}
